package com.engine.cn.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 原子类无锁并发
 */
public class AtomicIntegerTest {
    AtomicInteger count = new AtomicInteger(0);

    void increment() {
        count.incrementAndGet();
    }

    public static void main(String[] args) {
        List<Thread> threadList = new ArrayList<>();
        AtomicIntegerTest t = new AtomicIntegerTest();
        for (int i = 0; i < 100000; i++) {
            //所有线程都执行t::m方法
            threadList.add(new Thread(t::increment, "thread-" + i));
        }

        threadList.forEach(Thread::start);
        threadList.forEach(o -> {
            try {
                //让主线程等待调用o.join()
                o.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        System.out.println("count的值是" + t.count);
    }
}
